<?php
/**
 * Created by PhpStorm.
 * User: Lxx<779219930@qq.com>
 * Date: 2018/10/31
 * Time: 15:38
 */

namespace app\home\controller;


use app\admin\model\Push;
use app\home\model\ApprovalUser;
use app\home\model\NewsCommunication;
use app\home\model\NewsCommunicationDetail;
use app\home\model\WechatUser;
use com\wechat\QYWechat;
use com\wechat\TPQYWechat;
use think\Config;
use think\Controller;
use think\Db;
use think\Exception;
use think\Log;
use think\Model;

/**
 * Class Index
 * @package app\home\controller
 * 主页-菜单列表及入口
 */
class Index extends Controller
{
    public function index() {

        return $this->fetch();
    }

    /**
     * 用户登入获取信息
     */
    public function login(){
        // 获取用户信息
        $Wechat = new TPQYWechat(config('user'));
        $result = $Wechat->getUserId(input('code'), config('user.agentid'));
        if(empty($result['UserId'])) {
            session('userId', 'visitor');//游客userid为0
            session('name', '游客');
        } else {
            $userInfo = $Wechat->getUserInfo($result['UserId']);
            $data = [
                'userid' => $userInfo['userid'],
                'name' => $userInfo['name'],
                'mobile' => $userInfo['mobile'],
                'gender' => $userInfo['gender'],
                'avatar' => $userInfo['avatar'],
                'department' => $userInfo['department'][0], //只选第一个所属部门
                'status' => $userInfo['status'],
                'order' => $userInfo['order'][0],
            ];

            if(isset($userInfo['extattr']['attrs'])) {
                foreach ($userInfo['extattr']['attrs'] as $value) {
                    switch ($value['name']){
                        case "权限":
                            $data['permission'] = $value['value'] ? $value['value'] : 5;
                            break;
                        default:
                            break;
                    }
                }
                $data['extattr'] = json_encode($userInfo['extattr']);
            }else {
                $data['extattr'] = json_encode($userInfo['extattr']);
            }

            $wechatUser = new WechatUser();
            if ($wechatUser->checkUserExist($userInfo['userid'])) {
                $wechatUser->save($data, ['userid' => $userInfo['userid']]);
            } else {
                $wechatUser->save($data);
            }

            session('userId', $userInfo['userid']);
            session('name', $userInfo['name']);
            session('gender', $userInfo['gender']);
            session('avatar', $userInfo['avatar']);
            session('department', $userInfo['department'][0]);

            $this->redirect(session('requestUri'));
        }
    }

    public function push()
    {
        $map = ['status' => 0];
        $list = Push::where($map)->select();
        foreach ($list as $value) {
            //发送给服务号
            $Wechat = new TPQYWechat(Config::get($value['agentname']));
            $message = array(
                "touser" => $value['touser'],
                "msgtype" => $value['msgtype'],
                "agentid" => $value['agentid'],
                $value['msgtype'] => (array)json_decode($value['sendcontent']),
                "safe" => "0"
            );
            try {
                $msg = $Wechat->sendMessage($message);
                if ($msg['errcode'] == 0){
                    Push::where('id',$value['id'])->update(['status' => 1,'update_time' => time()]);
                    Log::write("审批消息发送：发送成功");
                }else{
                    Log::write("审批消息发送：发送失败");
                }
                Log::write($msg);
            }catch (Exception $exception) {
                $msg = $exception->getMessage();
                Log::write("消息发送崩溃：发送失败".$msg);
            }
        }
    }

    /**
     * 手动发放提醒
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function manual_send_message()
    {
        $class = input('class');
        $id = input('id');
        $setTable = $this->setTables($class);
        $detail =  Db::table($setTable['table'])->where(['id' => $id])->find();
        if($detail) {
            $map = [
                'class' => $class,
                'pid' => $id,
                'status' => 0
            ];
            $approvalUser = ApprovalUser::where($map)->select();
            if($approvalUser) {
                foreach ($approvalUser as $value) {
                    $this->setPushData(1,$class,$value['approval_user'],$detail);
                }
                return 1;
            }
        }
        return 0;
    }

    /**
     * 获取对应表格及信息
     */
    protected function setTables($class) {
        switch ($class) {
            case 1:
                $table = "zm_approval_leave";
                $model = "approval_leave";
                $model_detail = "";
                $class_text = "请假审批";
                $type = [1 => "事假", 2 => "护理假", 3 => "病假", 4 => "丧假", 5 => "工伤假", 6 => "产假", 7 => "婚嫁假",
                    8 => "哺乳假",9 => "年假",10 => "探亲假",11 => "独生子女假",12 => "育儿假",13 => "疗休养假"];
                $table_detail = "";
                break;
            case 2:
                $table = "zm_approval_seal";
                $model = "approval_seal";
                $model_detail = "";
                $class_text = "公章使用审批";
                $type = "";
                $table_detail = "";
                break;
            case 3:
                $table = "zm_approval_purchase";
                $table_detail = "zm_approval_purchase_detail";
                $model = "approval_purchase";
                $model_detail = "approval_purchase_detail";
                $class_text = "物资采购审批（内购）";
                $type = "";
                break;
            case 4:
                $table = "zm_approval_department";
                $model = "approval_department";
                $model_detail = "";
                $class_text = "部门联系单";
                $table_detail = "";
                $type = "";
                break;
            case 5:
                $table = "zm_approval_overtime";
                $model = "approval_overtime";
                $model_detail = "";
                $class_text = "加班申请审批";
                $type = [1 => "普通审批" , 2 => "应急审批"];
                $table_detail = "";
                break;
            default:
                return $this->error("无对应类别数据，请重新检查！");
                break;
        }
        $return = [
            'model' => $model,
            'model_detail' => $model_detail ? $model_detail : "",
            'table' => $table,
            'class_text' => $class_text,
            'type' => $type ? $type : "",
            'table_detail' => $table_detail ? $table_detail : "",
        ];
        return $return;
    }

    /**
     * 获取审批推送数据
     * $t 推送类型，1：审批 2：申请 ,3:审批完成推送
     * $class
     * $data
     */
    protected function setPushData($t = 1,$class,$user,$data) {
        switch ($class) {
            case 1:
                if($t == 1) {
                    $title = "您有新的审批需要处理！";
                    $type = 3;
                }else if($t == 2){
                    if($data['status'] == 1) {
                        $title = "您的审批申通已通过！";
                    }else {
                        $title = "您的审批申通被拒绝，请查看！";
                    }
                    $type = 2;
                }else {
                    $title = "有一条新的申请已完成审批,请注意查看!";
                    $type = 2;
                }
                $type_text = "[请假审批]";
                break;
            case 2:
                if($t == 1) {
                    $title = "您有新的审批需要处理！";
                    $type = 3;
                }else if($t == 2){
                    if($data['status'] == 1) {
                        $title = "您的审批申通已通过！";
                    }else {
                        $title = "您的审批申通被拒绝，请查看！";
                    }
                    $type = 2;
                }else {
                    $title = "有一条新的申请已完成审批,请注意查看!";
                    $type = 2;
                }
                $type_text = "[公章使用审批]";
                break;
            case 3:
                if($t == 1) {
                    $title = "您有新的审批需要处理！";
                    $type = 3;
                }else if($t == 2){
                    if($data['status'] == 1) {
                        $title = "您的审批申通已通过！";
                    }else {
                        $title = "您的审批申通被拒绝，请查看！";
                    }
                    $type = 2;
                }else {
                    $title = "有一条新的申请已完成审批,请注意查看!";
                    $type = 2;
                }
                $type_text = "[物资采购审批]";
                break;
            case 4:
                if($t == 1) {
                    $title = "您有新的审批需要处理！";
                    $type = 3;
                }else if($t == 2){
                    if($data['status'] == 1) {
                        $title = "您的审批申通已通过！";
                    }else {
                        $title = "您的审批申通被拒绝，请查看！";
                    }
                    $type = 2;
                }else {
                    $title = "有一条新的申请已完成审批,请注意查看!";
                    $type = 2;
                }
                $type_text = "[部门联系单审批]";
                break;
            case 5:
                if($t == 1) {
                    $title = "您有新的审批需要处理！";
                    $type = 3;
                }else if($t == 2){
                    if($data['status'] == 1) {
                        $title = "您的审批申通已通过！";
                    }else {
                        $title = "您的审批申通被拒绝，请查看！";
                    }
                    $type = 2;
                }else {
                    $title = "有一条新的申请已完成审批,请注意查看!";
                    $type = 2;
                }
                $type_text = "[加班申请审批]";
                break;
            default:
                Log::write("审批消息推送失败，不存在对应类别审批");
                break;
        }

        $pushData = [
//            'userid' => $user,
            'userid' => "18768112486",
            'title' =>  $title,
            'description' => "<div class=\"gray\">时间: ".date("Y-m-d H:i",time())."</div><div class=\"gray\">类型:".$type_text."</div><div class=\"highlight\">点击查看</div>",
            'url' => $_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME']."/home/approval/detail/type/".$type."/class/".$class."/id/".$data['id'],
        ];
        $this->approval_push($pushData);
    }

    /**
     * 推送
     */
    protected function approval_push($data){
        $send = [
            "title" => $data['title'],
            "description" => $data['description'],
            "url" => $data['url'],
        ];
        //发送给服务号
        $Wechat = new TPQYWechat(Config::get('approval'));
        $message = array(
            "touser" => $data['userid'],
//            "totag" => toTag,
            "msgtype" => 'textcard',
            "agentid" => config('approval.agentid'),
            "textcard" => $send,
            "safe" => "0"
        );
        $data = [
            'type' => 1,
            'agentname' => "approval",
            'touser' => $message['touser'],
            'msgtype' => $message['msgtype'],
            'agentid' => $message['agentid'],
            'sendcontent' => json_encode($message['textcard']),
            'safe' => $message['safe'],
        ];
        $res = Push::create($data);
        try {
            $msg = $Wechat->sendMessage($message);
            if ($msg['errcode'] == 0){
                Push::where('id',$res['id'])->update(['status' => 1,'update_time' => time()]);
                Log::write("审批消息发送：发送成功");
            }else{
                Log::write("审批消息发送：发送失败");
            }
            Log::write($msg);
        }catch (Exception $exception) {
            $msg = $exception->getMessage();
            Log::write("消息发送崩溃：发送失败".$msg);
        }
    }


    //更新数据
    public function synDocumentsData()
    {
        $page = input('page',1);
        $limit = 200;
        $offset = ($page - 1) * $limit;
        $Model = new NewsCommunicationDetail();
        $mainModel = new NewsCommunication();
        $list = $mainModel->where('status','egt',0)
            ->limit($offset,$limit)->select();
        $total = count($list);
        $i = 0;
        $j = 0;
        foreach ($list as $value) {
            //归档
            $allCount2 = $Model->where(['communication_id' => $value['id'],'permission' => 3])->count();
            $finalCount2 =$Model->where(['communication_id' => $value['id'],'permission' => 3,'status' => 2])->count();
            if($allCount2 > 0 && $allCount2 == $finalCount2) {
                $mainModel->where('id',$value['id'])->update(['status' => 2]);
                $i++;
            }else {
                //进行中
                $detail = $Model->where(['communication_id' => $value['id'],'permission' => 1])->find();
                if(!empty($detail) && $detail['status'] > 0) {
                    $mainModel->where('id',$value['id'])->update(['status' => 1]);
                    $j++;
                }
            }
        }
        echo "全部记录:".$total."，已更新为归档：".$i."，已更新为轮阅中：".$j."，未改动".($total-($i+$j));
    }
}